package com.atguigu.day09;

import com.atguigu.utils.OrderEvent;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

// 使用flink cep实现订单超时检测
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<OrderEvent> stream = env
                .addSource(new SourceFunction<OrderEvent>() {
                    @Override
                    public void run(SourceContext<OrderEvent> ctx) throws Exception {
                        OrderEvent e1 = new OrderEvent("order-1", "create-order", 1000L);
                        ctx.collectWithTimestamp(e1, e1.ts);
                        Thread.sleep(1000L);
                        OrderEvent e2 = new OrderEvent("order-2", "create-order", 2000L);
                        ctx.collectWithTimestamp(e2, e2.ts);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(3000L));
                        Thread.sleep(1000L);
                        OrderEvent e3 = new OrderEvent("order-1", "pay-order", 4000L);
                        ctx.collectWithTimestamp(e3, e3.ts);
                        Thread.sleep(1000L);
                        ctx.emitWatermark(new Watermark(7000L));
                        Thread.sleep(1000L);
                    }

                    @Override
                    public void cancel() {

                    }
                });

        // 定义模板
        Pattern<OrderEvent, OrderEvent> pattern = Pattern
                .<OrderEvent>begin("create")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("create-order");
                    }
                })
                .next("pay")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("pay-order");
                    }
                })
                // 要求两个事件在五秒钟之内发生
                .within(Time.seconds(5));

        // 在流上使用模板匹配
        PatternStream<OrderEvent> patternStream = CEP.pattern(
                stream.keyBy(r -> r.orderId),
                pattern
        );

        SingleOutputStreamOperator<String> result = patternStream
                .flatSelect(
                        // 侧输出流用来接收超时未支付的订单信息
                        new OutputTag<String>("timeout-order") {
                        },
                        // 用来将超时未支付的订单信息发送到侧输出流
                        new PatternFlatTimeoutFunction<OrderEvent, String>() {
                            @Override
                            public void timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                                // 超时未支付的订单流中，只有create-order事件，没有pay-order事件
                                OrderEvent create = pattern.get("create").get(0);
                                // collect方法将数据发送到侧输出流
                                out.collect("订单" + create.orderId + "未支付");
                            }
                        },
                        // 处理的是未超时支付的订单
                        new PatternFlatSelectFunction<OrderEvent, String>() {
                            @Override
                            public void flatSelect(Map<String, List<OrderEvent>> pattern, Collector<String> out) throws Exception {
                                OrderEvent create = pattern.get("create").get(0);
                                OrderEvent pay = pattern.get("pay").get(0);
                                // 向下游发送数据
                                out.collect("订单" + create.orderId + "在" +
                                        "" + create.ts + "创建订单，在" +
                                        "" + pay.ts + "支付订单");
                            }
                        }
                );

        result.getSideOutput(new OutputTag<String>("timeout-order"){}).print();

        result.print();

        env.execute();
    }
}
